package com.sun.umbrella.manager.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Jay
 * @version v1.0
 * @description 密码工具类
 * @date 2018-05-30 13:59
 */
@Slf4j
public class PasswordUtil {


    /**
     * hash的次数
     */
    public static final Integer HASH_COUNT= 1024;

    /**
     * 加密
     *
     * @param password
     * @param salt
     * @return
     */
    public static String makePassword(String password, String salt) {
        return new SimpleHash("MD5", password, ByteSource.Util.bytes(salt), HASH_COUNT).toHex();
    }


    /**
     * MD5 加密
     *
     * @param str
     * @return
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException caught!", e);
            return null;
        } catch (UnsupportedEncodingException e) {
            log.error("MD5加密失败", e);
            return null;
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString();
    }

    /**
     * 格式化MD5串
     *
     * @param str
     * @return
     */
    public static String generageMD5(String str){
        return new StringBuilder(getMD5Str(str))
                .insert(8,"-")
                .insert(17,"-")
                .insert(26,"-")
                .toString();
    }
}
